<template>
  <div class="vehicle-map" ref="map">
    <div id="container1">
      <div id='district'>
        <input ref="districtInput" type="text" :value="district" placeholder="请输入地址" @keypress="getKey">
        <button @click="placeSearch(district)">搜索</button>
        <div class="popover" ref="popover" v-if="showPopover">
          <ul class="popUls">
            <li v-for="item in poisList" :key="item.id" @click="getAddress">{{ item.name }}</li>
          </ul>
          <van-pagination v-model="obj.currentPage" :total-items="obj.totalSize" :items-per-page="obj.pageSize" :show-page-size="2" force-ellipses @change="change">
            <template #prev-text>
              <van-icon name="arrow-left" />
            </template>
            <template #next-text>
              <van-icon name="arrow" />
            </template>
            <template #page="{ text }">{{ text }}</template>
          </van-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// 因为获取到坐标查询不到地址，所以需要将安全密钥加上去
window._AMapSecurityConfig = {
  securityJsCode: '237716e4a44b4c1b1e45e9280e7f189f'
}

export default {
  name: "vehicleMap",
  data() {
    return {
      map: null,
      center: [116.397428, 39.90923], // 默认坐标
      location: '', // 地址
      cityinfo: '', // 城市
      district: '',
      lnglat: '[113.284218,23.134583]',
      showPopover: false, // 弹框的显示状态
      poisList: [], // 搜索到的数据
      obj: {
        currentPage: 1, // 当前页数
        pageSize: 10,
        totalSize: 100 // 总页数
      },
      queryLocation: ''
    }
  },
  mounted() {
    this.initMap();
  },
  // 监听器，当监听的变量发生变化时执行代码监听
  watch: {
    obj: {
      handler: function() {
        this.placeSearch();
      },
      deep: true
    }
  },
  methods: {
    getAddress(e) {
      let that = this;
      this.queryLocation = e.target.innerHTML;
      let geocoder = new window.AMap.Geocoder({
        // city: "010" // 城市设为北京，默认：“全国”
      });

      let marker = new window.AMap.Marker();
      geocoder.getLocation(e.target.innerHTML, function(status, result) {
        that.lnglat = [result.geocodes[0].location.lng, result.geocodes[0].location.lat];
        console.log('搜索拿到的经纬度',that.lnglat);
        that.$emit('acceptLocation', [result.geocodes[0].formattedAddress, result.geocodes[0].addressComponent.city === ''?result.geocodes[0].addressComponent.province:result.geocodes[0].addressComponent.city, that.lnglat]);
        that.showPopover = false;
        if (status === 'complete'&&result.geocodes.length) {
          let lnglat = result.geocodes[0].location;

          marker.setPosition([lnglat.lng, lnglat.lat]);
          that.map.add(marker);
          that.map.setFitView(marker);
        }else{
          console.error('根据地址查询经纬度失败');
        }
      });
    },
    // 输入框回车事件
    getKey() {
      if(event.keyCode === 13) {
        this.placeSearch();
      }
    },
    // 点击上一页下一页触发的事件
    change(page) {
      this.obj.currentPage = page;
    },
    // 地址搜索
    placeSearch() {
      this.district = ''
      let _this = this;
      this.district = this.$refs.districtInput.value;

      if(!this.district) {
        _this.showPopover = false;
      }else {
        let placeSearch = new window.AMap.PlaceSearch({
          pageSize: this.obj.pageSize, // 每页条数，默认10，范围1-50
          pageIndex: this.obj.currentPage // 范围： 1 - Math.ceil(count/10)
        });

        placeSearch.search(this.$refs.districtInput.value, function(status, result) {
          _this.obj.totalSize = result.poiList.count;
          _this.poisList = result.poiList.pois; // 确定搜索到的十条数据

          if(_this.district) {
            _this.showPopover = true; // 让下拉框显示
          }else {
            _this.showPopover = false; // 让下拉框消失
          }
        })
      }
    },
    // 点击事件,给地图绑定点击事件
    clickOn() {
      this.map.on('click', this.showClick);
    },
    // 地图点击事件
    showClick(e) {
      let that = this;
      let lnglat = [e.lnglat.lng, e.lnglat.lat]; // 获取坐标
      console.log('地图点击拿到的经纬度', lnglat);
      that.lnglat = lnglat;

      // 标记
      let marker = new window.AMap.Marker();
      this.map.add(marker); // 在地图中添加标记
      marker.setPosition(e.lnglat); // 将标记放到我们点击的位置上

      let geocoder = new window.AMap.Geocoder({
        // city: "010", // 城市设为北京，默认：“全国”
        radius: 1000 // 范围，默认：500
      });
      // getAddress 实现逆地理编码
      geocoder.getAddress(lnglat, function(status, result) {
        if (status === 'complete' && result.regeocode) {
          // 把当前点击选中的城市和具体的地址传给父组件
          that.$emit('acceptLocation', [result.regeocode.formattedAddress, result.regeocode.addressComponent.city === ""?result.regeocode.addressComponent.province:result.regeocode.addressComponent.city, that.lnglat]);
        }else{
          console.error('根据经纬度查询地址失败')
        }
      });
    },
    // 初始化地图,让地图显示出来
    initMap() {
      AMapLoader.load({
        key: "3ec0f4b64da67a9e6ade01ba12078cf8", // 设置您的key
        version: "2.0",
        plugins: ["AMap.ToolBar", "AMap.Driving", "AMap.CitySearch", "AMap.Geocoder", "AMap.PlaceSearch"],
        AMapUI: {
          version: "1.1",
          plugins: []
        },
        Loca: {
          version: "2.0"
        }
      })
        .then((AMap) => {
          this.map = new AMap.Map("container1", {
            viewMode: "3D",
            zoom: 11
            // center: this.center
          });
          this.clickOn(); // 给地图添加点击事件
        })
        .catch((e) => {
          console.log(e);
        });
    }
  },
  destroyed() {
    this.map.destroy();
    this.map = null;
  }
};
</script>
<style lang="scss" scoped>
.vehicle-map {
  width: 100%;
  height: 100%;
  #container1 {
    width: 100%;
    height: 100%;
    position: relative;
    #district {
      position: absolute;
      top: 10px;
      left: 20px;
      z-index: 1;
      display: flex;
      flex-flow: row nowrap;
      width: 230px;
      height: 34px;
      background-color: pink;
      input {
        border: none;
        padding: 0 4px;
        box-sizing: border-box;
        flex: 1;
      }
      button {
        width: 100%;
        font-size: 14px;
        border: none;
      }
      .popover /deep/ {
        position: absolute;
        top: 34px;
        left: 0;
        background-color: #fff;
        width: 100%;
        padding: 4px;
        box-sizing: border-box;
        .popUls {
          width: 100%;
          // height: 200px;
          // overflow-y: auto;
          li {
            width: 100%;
            height: 25px;
            line-height: 25px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .van-pagination {
          font-size: 12px;
          li {
            &:first-of-type, &:last-of-type {
              font-size: 10px;
              width: 100%;
              padding: 0;
            }
          }
        }
      }
    }
  }
}
</style>